package freaks.terah.gui;

import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import freaks.terah.model.Data;
import freaks.terah.model.FileIO;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class NewFrame extends JPanel implements ActionListener, KeyListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextField nameField;
	private JTextField idField;
	private JButton btnAdd;
	private JButton btnRemove;
	private JButton btnContinue;
	JList list;
	private Gui guiParent;
	private JLabel errorText;
	/**
	 * Create the panel.
	 */
	public NewFrame(Gui aParent) {
		setLayout(null);
		guiParent = aParent;
		JLabel lblName = new JLabel("Name:");
		lblName.setBounds(205, 79, 61, 16);
		add(lblName);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(346, 61, 80, 172);
		add(scrollPane);

		list = new JList();
		list.setModel(guiParent.getPlayers());
		scrollPane.setViewportView(list);

		nameField = new JTextField();
		nameField.setBounds(254, 73, 80, 28);
		add(nameField);
		nameField.addKeyListener(this);
		nameField.setColumns(10);

		btnAdd = new JButton("Add");
		btnAdd.addActionListener(this);
		btnAdd.setBounds(239, 114, 55, 29);
		add(btnAdd);

		btnRemove = new JButton("Remove");
		btnRemove.addActionListener(this);
		btnRemove.setBounds(223, 155, 87, 29);
		add(btnRemove);

		JLabel lblPlayers = new JLabel("Players");
		lblPlayers.setBounds(285, 33, 61, 16);
		add(lblPlayers);

		JLabel lblGameId = new JLabel("Game ID:");
		lblGameId.setBounds(20, 79, 61, 16);
		add(lblGameId);

		idField = new JTextField();
		idField.setBounds(82, 73, 87, 28);
		add(idField);
		idField.setColumns(10);

		btnContinue = new JButton("Continue");
		btnContinue.addActionListener(this);
		btnContinue.setBounds(158, 251, 117, 29);
		add(btnContinue);

		JLabel lblNewLabel = new JLabel("Game idenfier (0-127)");
		lblNewLabel.setBounds(20, 114, 149, 16);
		add(lblNewLabel);

		errorText = new JLabel("");
		errorText.setForeground(Color.RED);
		errorText.setBounds(20, 217, 274, 16);
		add(errorText);
	}
	@Override
	public void actionPerformed(ActionEvent arg0) 
	{
		if (arg0.getSource() == btnAdd)
		{
		    String value = nameField.getText().trim();
			if (!value.contentEquals(""))
			{
		        guiParent.getPlayers().addElement(value);
		        nameField.setText("");
			}
		}
		
		if (arg0.getSource() == btnRemove)
		{
			if (list.getSelectedIndex() != -1)
			{
				guiParent.getPlayers().remove(list.getSelectedIndex());
			}
		}
		
		if (arg0.getSource() == btnContinue)
		{
			try
			{
				int id = Integer.parseInt(idField.getText());
				int nbPlayers = guiParent.getPlayers().getSize();
				
				if (id < 0 || id > 127)
				{
					errorText.setText("There ID must be in the 0-127 range.");
					return;
				}
				
				if (nbPlayers < 2)
				{
					errorText.setText("There must be at least 2 players.");
					return;
				}
				
				//DONE
				generateCodes();
				guiParent.setID(id);
				errorText.setText("");
				guiParent.setNewPlayerFrame(2, 1);
			} catch (Exception e)
			{
				errorText.setText("The ID must be a valid number");
			}
		}
	}
	
	private void generateCodes() throws IOException
	{
		String fileString = "Server codes\n-------------\n";
		Data[] thePlayerNum = new Data[1];
		Data[] theData = new Data[3 + guiParent.getPlayers().getSize()];
		theData[0] = new Data(Integer.parseInt(idField.getText()));
		theData[1] = new Data(3);
		theData[2] = new Data(guiParent.getPlayers().getSize());
		
		for (int i = 0; i < guiParent.getPlayers().getSize(); i++)
		{
			theData[3+i] = new Data((String) guiParent.getPlayers().get(i));
		}
		
		FileIO io = new FileIO();
		
		for (int i = 0; i < guiParent.getPlayers().getSize(); i++)
		{
			thePlayerNum[0] = new Data(i+1);
			String playerString = io.encode(thePlayerNum);
			if (playerString.length() == 1)
				playerString += "0";
			
			String dataString = io.encrypt(io.encode(theData), 1, i+1);
			fileString += (String) guiParent.getPlayers().get(i) + ": " + playerString + dataString + "\n";
		}
		
		fileString += "------------";
		
		File file = new File("serverString.txt");
		
		FileOutputStream stream = new FileOutputStream(file);
		stream.write(fileString.getBytes());
		stream.close();
	}
	
	@Override
	public void keyPressed(KeyEvent arg0) {
	}
	
	@Override
	public void keyReleased(KeyEvent arg0) {
	}
	
	@Override
	public void keyTyped(KeyEvent arg0) {
		if (arg0.getKeyChar() == '\n' || arg0.getKeyChar() == '\r')
		{
			String value = nameField.getText().trim();
			if (!value.contentEquals(""))
			{
		        guiParent.getPlayers().addElement(value);
		        nameField.setText("");
			}
		}
	}
}
